#===============================================
# Code written by Joe France (joeprogram.com)
# Released under code.google.com/p/video-scholar/
# with the MIT license (aka, the do-whatever-you-want-with-it license)
#===============================================

import pyglet

from CompoundGUI import CompoundGUI
from lxml import etree
from Mark import Mark

class MarkGroup( CompoundGUI ):
	'''
	A Mark Group keeps a collection of marks
	Each of these marks are used to denote the same event
	And have the same shading
	'''
	
	def __init__( self, timeline, hot_key ):
		'''
		A mark group requires both a timeline and a hot_key
		The mark group is the draw child of the timeline
		but listens to the hotkey as to when to draw new marks
		'''
	
		super( MarkGroup, self ).__init__()
	
		self.batch = pyglet.graphics.Batch()
		self.timeline = timeline
		self.hot_key = hot_key
		self.marks = []
		
		self.hot_key.set_mark_group( self )
		
	def add_mark( self ):
		
		mark = Mark( self.timeline.video_player.get_time(), color = self.hot_key.get_color(), batch = self.batch )
		self.position_mark( mark )	
		self.marks.append( mark )
		
	def position_mark( self, mark ):
		'''
		Sets a mark to the proper position in the timeline
		'''
		mark.set_coordinates( x = self.timeline.x + ( self.timeline.bar.get_width() * mark.get_timestamp() / self.timeline.duration ) , y = self.timeline.y )
		
	def import_xml( self, node ):
		'''
		Imports all the marks from a node
		'''

		for mark_node in node.findall( 'mark' ):
			mark = Mark( mark_node.get('timestamp'), color = self.hot_key.get_base_color(),  batch = self.batch)
			self.position_mark( mark )			
			self.marks.append( mark )

	def export_xml( self, node ):
		'''
		Exports all the marks to xml
		The node we get here is not the same as the one we export to - 
		our first step is to locate that node
		'''
		
		hot_key_node = node.find('hot_key[@key="%s"]' % self.hot_key.get_key() )
		for mark in self.marks:
			mark_node = etree.SubElement( hot_key_node, 'mark' )
			mark_node.set('timestamp', str(mark.get_timestamp()))

	def draw( self ):
		self.batch.draw()


					